#include "frmtodo.h"
#include "ui_frmtodo.h"

#include "todoparser.h"
#include "todoformatter.h"

#include <QDebug>

#include <QMessageBox>
#include <QFile>
#include <QDir>

#define MACOSX

FrmTodo::FrmTodo(QString fileName, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FrmTodo),
    _fileName(fileName)
{
    ui->setupUi(this);

    ui->lblDelete->setText("<a href='delete'>X</a>");
    QFont font("Monospace");
    font.setStyleHint(QFont::TypeWriter);
    ui->txtTasks->setFont(font);
    ui->txtTasks->setFontPointSize(9.0);

#ifdef MACOSX
    //ui->txtTasks->setFontFamily("Monaco");
#endif

    connect(ui->txtTasks, SIGNAL(itemDoubleClicked(int)), this, SLOT(itemDblClicked(int)));

    connect(ui->lneNumber, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
    connect(ui->lneDesc, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
    connect(ui->lneData, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
    connect(ui->lneImportancia, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
    connect(ui->lblDelete, SIGNAL(linkActivated(QString)), this, SLOT(linkClicked(QString)));

    /*
    QList<TodoItemPtr> list;
    list << _todoParser.parseLine("2|(B)|ASDdas das das d|N|2014-01-23|N");
    list << _todoParser.parseLine("3|(A)|Agora um teste|N|2014-01-23|S");
    list << _todoParser.parseLine("4|(B)|Descrição do meu item|S|2014-01-23|N");
    list << _todoParser.parseLine("5|(C)|Thiago Massari Guedes|N|2014-01-23|N");
    list << _todoParser.parseLine("12|(D)|jdskjd sadaskdjaskjd|N|2014-01-23|N");
    */

    loadTodoList(_fileName);

}

FrmTodo::~FrmTodo()
{
    delete ui;
}

bool FrmTodo::loadTodoList(QString fileName)
{
    TodoParser todoParser(_manager);

    _manager.clear();
    bool ret = todoParser.parseFile(fileName);

    if( ret ) {
        _renderTodoList(false);
    } else {
        if( QFile(fileName).exists() ) {
            QMessageBox::critical(this, "Erro abrindo arquivo", "Erro abrindo arquivo de todos - " + fileName);
        } else {
            QMessageBox::information(this, "Arquivo de dados", "<font color='red'>Arquivo de dados não existe</font><br>Vamos criar<br>" + fileName);
            ret = true;
        }
    }

    if( ret ) {
        QString name;
        QDir d;
        name = d.absoluteFilePath(fileName);
        if( name.contains('/') ) {
            int pos = name.lastIndexOf('/');
            name = name.mid(pos+1);
        }
        this->setWindowTitle("ToDo Desktop - " + name);
    }

    return ret;
}

void FrmTodo::itemDblClicked(int number) {
    qDebug() << "open"<< number;

    TodoItemPtr item = _manager.getTodo(number);
    if( item.isNull() ) return;

    ui->lneNumber->setText( QString::number(item->code) );
    ui->lneDesc->setText( item->description );
    ui->lneImportancia->setText( item->priorityToString() );
    ui->lneData->setText( item->dateToString() );

    ui->chkUrgente->setChecked( item->urgent );

}

void FrmTodo::returnPressed()
{
    TodoItemPtr item(new TodoItem(
                         ui->lneNumber->text(), ui->lneImportancia->text(), ui->lneDesc->text(),
                         ui->chkUrgente->isChecked()?"S":"N", ui->lneData->text(), ""
                         ));
    _manager.addTodo(item);

    _renderTodoList();

    ui->lneNumber->clear();
    ui->lneDesc->clear();
    ui->lneImportancia->clear();
    ui->lneData->clear();

    ui->chkUrgente->setChecked( false );

}

void FrmTodo::_renderTodoList(bool saveFile)
{
    TodoParser todoParser(_manager);

    if( saveFile )
        todoParser.saveFile(_fileName);

    const TodoManager::TodoMap &todoMap = _manager.getTodoMap();

    TodoFormatter formatter;
    for(TodoItemPtr item : todoMap) {
        formatter.addLine(*item);
    }

    formatter.calculateSizes();
    QPair<int, QString> header = formatter.getHeader();

    ui->txtTasks->clear();
    ui->txtTasks->insertHtml(header.second);
    ui->txtTasks->insertHtml(QString().fill('-', header.first) + "<br>");

    int total = formatter.getCount();
    for(int i=0; i < total; i++) {
        ui->txtTasks->insertHtml( formatter.getLine(i) );
    }

}

void FrmTodo::linkClicked(QString href)
{
    int ret = href.compare("delete", Qt::CaseInsensitive);
    if(ret == 0) {
        int code = ui->lneNumber->text().toInt();
        if( code == 0 )
            return;

        bool ret = _manager.delTodo(code);
        if( !ret ) {
            QString erro = QString("Erro deletando todo %1 - Registro não encontrado").arg(code);
            QMessageBox::critical(this, "Erro deletando ToDo", erro);
        } else {
            _renderTodoList();
        }
    }
}
